package com.example.administrator.szb.activity.supei;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.pickerview.TimePickerView;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.GZXYActivity;
import com.example.administrator.szb.activity.Success2Activity;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.activity.supei.presenter.SuPeiPresenter;
import com.example.administrator.szb.activity.supei.view.SuPeiView;
import com.example.administrator.szb.bean.BusinessSuPei;
import com.example.administrator.szb.bean.BusinessSuPeiSelect;
import com.example.administrator.szb.bean.Messages;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.JsonUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.BottomListPop;
import com.example.administrator.szb.util.Contants;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.IosDiaolog;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.view.MyListView;
import com.example.administrator.szb.view.TimePickUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SuPeiNewActivity extends MVPBaseActivity<SuPeiView,SuPeiPresenter> implements SuPeiView {

    private TextView bar_title,sqxm_text_bmxy;
    List<BusinessSuPei> businessSuPei;
    BusinessSuPeiSelect listMap;
    private TextView tv_tips;

    private LinearLayout ll_time;
    private TextView tv_time;
    private EditText et_name;
    private EditText et_phone;
    private EditText tv_content;
    private Button send_btn;
    private MyListView listView;
    private Map<Integer,String> select = new HashMap<>();
    private int mold=1;
    private int id=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_su_pei_new);
    }

    @Override
    protected SuPeiPresenter createPresenter() {

        mPresenter = new SuPeiPresenter(this);
        return mPresenter;
    }

    @Override
    protected void initView() {
        sqxm_text_bmxy = findViewById(R.id.sqxm_text_bmxy);
        id=getIntent().getIntExtra("speed_id",0);
        mold = getIntent().getIntExtra("mold",1);
        tv_tips = findViewById(R.id.tv_tips);
        tv_tips.setText("");
        tv_tips.setVisibility(View.GONE);
        bar_title = findViewById(R.id.bar_title);
        bar_title.setText("发布项目");
        ll_time = (LinearLayout) findViewById(R.id.ll_time);
        tv_time = (TextView) findViewById(R.id.tv_time);
        et_name = (EditText) findViewById(R.id.et_name);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_phone.setText(SPUtils.getDatasString(SPUtils.USER_PHONE));
        tv_content = (EditText) findViewById(R.id.tv_content);
        setEditEvent(tv_content,R.id.tv_content);
        send_btn = (Button) findViewById(R.id.send_btn);
        listView = findViewById(R.id.listView);
        //tv_tips.setText(businessSuPei.getWarnbus());
    }

    @Override
    protected void initEvent() {
        sqxm_text_bmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_web = new Intent(context,GZXYActivity.class);//额，
                intent_web.putExtra("title","保密承诺");
                intent_web.putExtra("id",2);
                startActivity(intent_web);
            }
        });
        ll_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickUtil.initCustomTimePicker(tv_time,0);
            }
        });
        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.send();
            }
        });

    }

    @Override
    protected void initData() {

        mPresenter.requestUserInfo();

        //DialogUtil.showIsoProgressbar(context,"加载数据中...");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("speed_id", id + "");
        //map.put("counselor_id", counselor_id + "");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.SUPEI_DATA;
        HttpUtils.post2(activity,url, map,0, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String strs2) {
                //DialogUtil.dialog_ios.dismiss();
                Messages messages = JsonUtils.getMessages2(strs2.toString());
                String str = JsonUtils.JsonParse(messages);
                if (messages.getResult()==1){
                    List<String> stringList = JSON.parseArray(messages.getMsginfo(),String.class);
                    if (stringList!=null&&stringList.size()>0&&stringList.get(0).length()>0){
                        tv_tips.setText(stringList.get(0));
                        tv_tips.setVisibility(View.VISIBLE);
                    }

                    List<String> liststr = JSON.parseArray(str,String.class);

                    businessSuPei = JSON.parseArray(liststr.get(0),BusinessSuPei.class);
                    if (liststr.get(1).equals("[]")){
                        liststr.set(1,null);
                    }

                    listMap =JSON.parseObject(liststr.get(1),new TypeReference<BusinessSuPeiSelect>(){});
                    initDatas();
                }

            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }

    protected void initDatas() {

        for (int a=0;a<businessSuPei.size();a++){
            select.put(a,null);
        }



        SuPeiAdapter adapter=new SuPeiAdapter(context,businessSuPei);
        adapter.setListener(new SuPeiAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position, View view) {
                QTLog.e(position+","+businessSuPei.get(position).getDatatype());
                final TextView editText = view.findViewById(R.id.et_title2);
                if (businessSuPei.get(position).getDatatype()==4){
                    //时间相关
                    TimePickUtil.initCustomTimePicker2(context,0, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {//选中事件回调
                            editText.setText(TimePickUtil.getTime(date));
                            select.put(position,TimePickUtil.getTime(date));
                        }
                    });
                }else if (businessSuPei.get(position).getDatatype()==1){
                    QTLog.e(businessSuPei.get(position).getDatatype());
                    if (listMap==null){
                        return;
                    }
                    //有弹窗子项
                    List<BusinessSuPeiSelect.SelectItem> suPeiSelect = listMap.getSelect().get(businessSuPei.get(position).getTitle());
                    if (suPeiSelect==null){
                        return;
                    }
                    final List<String> stringList = new ArrayList<String>();
                    for (int i=0;i<suPeiSelect.size();i++){
                        stringList.add(suPeiSelect.get(i).getTitle());
                    }
                    QTLog.e(stringList);
                    if (stringList.size()==0){
                        return;
                    }
                    BottomListPop.show(listView, SuPeiNewActivity.this, stringList, new BottomListPop.OnItemClickListener() {
                        @Override
                        public void onItemClick(int pos) {
                            editText.setText(stringList.get(pos));
                            select.put(position,stringList.get(pos));
                        }
                    });
                }
            }

            @Override
            public void onEditChange(int pos, String str) {
                select.put(pos,str);
            }
        });
        listView.setAdapter(adapter);
    }

    @Override
    public boolean canSubmit() {
        boolean canDo = true;
        String tipstr = "";
        if (select==null){
            tipstr="数据异常";
            return false;
        }
        for(Map.Entry<Integer, String> entry:select.entrySet())
        {
            if (TextUtils.isEmpty(entry.getValue())){
                canDo = false;
                tipstr = businessSuPei.get(entry.getKey()).getAskfor();
                if (businessSuPei.get(entry.getKey()).getDatatype()==2||businessSuPei.get(entry.getKey()).getDatatype()==3){
                    tipstr = businessSuPei.get(entry.getKey()).getAskfor()+businessSuPei.get(entry.getKey()).getTitle();
                }

                break;
            }
            //System.out.println("Key:"+ entry.getKey()+ " Value:"+entry.getValue());
        }
        if (!canDo){
            DialogUtil.showToast(context,tipstr);
            return canDo;
        }

        if (TextUtils.isEmpty(tv_time.getText().toString().trim())){
            tipstr = "请选择日期";
            canDo = false;
        }else if (TextUtils.isEmpty(et_name.getText().toString().trim())){

            tipstr = "请输入联系人";
            canDo = false;
        }else if (!Contants.isMobileNO(et_phone.getText().toString().trim())){
            tipstr = "请输入正确的手机号";
            canDo = false;
        }
        if (!canDo){
            DialogUtil.showToast(context,tipstr);
            return canDo;
        }
        if (mold==3){
            if (TextUtils.isEmpty(tv_content.getText().toString().trim())){
                DialogUtil.showToast(context,"请输入备注");
                canDo=false;
                return canDo;
            }

        }
        return canDo;
    }

    @Override
    public Map<String, Object> getSubmitInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("type",id);
        map.put("user_id",SPUtils.getUserId());
        map.put("contact",et_name.getText().toString().trim());
        map.put("tel",et_phone.getText().toString().trim());
        map.put("end_time",tv_time.getText().toString().trim());
        map.put("other_require",tv_content.getText().toString().trim());

        int n=0;
        String str = "{";
        Map<Integer,String> map1 = new HashMap<>();
        for(Map.Entry<Integer, String> entry:select.entrySet())
        {
            String tmp="\""+businessSuPei.get(entry.getKey()).getTitle()+"\":"+"\""+entry.getValue()+"\"";
            map1.put(businessSuPei.get(entry.getKey()).getId(),entry.getValue()+businessSuPei.get(entry.getKey()).getUnits());
            if (n!=select.size()-1){
                tmp+=",";
            }
            str+=tmp;
            n++;
        }
        str += "}";
        if (map1.size()==0){

        }else {
            map.put("project_details",JSON.toJSON(map1));
        }

        map.put("app","android");
        return map;
    }

    @Override
    public void onSuccesss(String str) {
        DialogUtil.showToast(context,str);
        Intent intent = new Intent(this, Success2Activity.class);
        intent.putExtra("titles","发布成功");
        //intent.putExtra("content","")
        startActivity(intent);
        finish();
    }

    @Override
    public void onFails(String string) {
        DialogUtil.showToast(context,string);
    }

    @Override
    public void showName(String names) {
        et_name.setText(names);
    }

    @Override
    public void onFinish(View view) {
        back();
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private void back(){
        iosDiaolog.setMsgs("您的项目尚未提交,是否选择离开?");
        iosDiaolog.setLeftButton("离开");
        iosDiaolog.setRightButton("继续填写");
        iosDiaolog.setLeftClick(new IosDiaolog.OnIosDialogClickListener() {
            @Override
            public void onClick(String str, PopupWindow popupWindows) {
                finish();
            }
        });
        iosDiaolog.show(ll_time);
    }
}
